from enum import Enum
from typing import Tuple, Any
from werkzeug.exceptions import BadRequest
from flask_sqlalchemy.pagination import Pagination


# 响应Code的类型枚举
class ResponseType(Enum):
    success: Tuple[int, str] = (200, "成功")
    server_error: Tuple[int, str] = (1001, "服务端异常")
    token_error: Tuple[int, str] = (1002, "登录失效，请重新登录")
    not_login: Tuple[int, str] = (1003, "未登录")
    field_missing: Tuple[int, str] = (1004, "字段缺失")
    field_error: Tuple[int, str] = [1005, "字段传参异常"]
    user_operate_error: Tuple[int, str] = [1006, "用户操作异常"]


def get_response(type: ResponseType = ResponseType.success, data=None, msg: str = None) -> dict:
    message = type.value[1]
    if msg is not None:
        message = msg

    return {
        'code': type.value[0],
        'data': data,
        'msg': message
    }


def get_page_response(key: str, data: Any, pagination: Pagination) -> dict:
    result = {
        key: data,
        'pageInfo': {
            'pageNO': pagination.page,
            'totalPage': pagination.pages,
            'total': pagination.total,
            'pageSize': pagination.per_page
        }
    }
    return get_response(ResponseType.success, data=result)


def get_error_response(e: Exception) -> dict:
    if isinstance(e, BadRequest):
        error_msg = f"{e.data.get('message')}"
        return get_response(ResponseType.field_error, msg=error_msg)
    else:
        return get_response(ResponseType.server_error, msg=f"{e}")


if __name__ == '__main__':
    print(get_response(type=ResponseType.success))
